from flask import Blueprint, request, render_template, redirect, url_for, jsonify, current_app, flash
from app import db
from ..models import Case, Patient, Doctor, Ward, Bed, Department, Takes, Request, Disease
import numpy as np
import json
from .. import utils

api_bp = Blueprint('api', __name__)

@api_bp.route('/sorted_departments/<department_name>',methods=['GET'])
def Get_sorted_departments(department_name):
    ##department_id 表示需要床位的科室id 
    ##对于department_id 计算出其他所有科室的推荐分数 根据分数排序并返回json数据

    ##------------------------------------------------------------------------------------------

    ##1. 得出除department_id之外的所有科室列表
    List_department_name = [x.dept_name for x in Department.query.filter(Department.dept_name != department_name).distinct().all()]

    ##2. 计算所有科室床位使用率
    Dict_usage = {x.dept_name:1-(x.bed_used/x.bed_total) for x in Department.query.filter(Department.dept_name != department_name).all()}  ##科室床位使用率

    ##2. 计算所有科室的平均住院时长和病人预计住院时长之差
    Dict_time = {x:0 for x in List_department_name}

    ##3. 统计科室间物理距离
    Dict_distance = {x:0 for x in List_department_name}

    ##4. 排序并返回
    Dict_score = { x:0 for x in List_department_name}

    for dept_name in List_department_name:   ##计算所有科室的推荐分数
        Dict_score[dept_name] = Dict_usage[dept_name] * 100 * 0.5 + Dict_time[dept_name] * 0.4 + Dict_distance[dept_name] * 0.1  ##根据床位使用率和平均住院时长差计算分数
    
    Score = sorted(Dict_score.items(),key = lambda x:x[1],reverse=True)

    result = []
    for x in Score:
        result.append({"dept_name":x[0],"score":x[1]})


    # print(Dict_score)

    return utils.custom_jsonify((result))



@api_bp.route('/borrow/<department_name>/doctor_info') 
def Get_borrow_doctorinfo(department_name):
    ##查询department_name对应科室中的医生信息
    ##计算得到医生的空床数量
    List_doctor_id = [x.doctor_id for x in Doctor.query.filter(Doctor.dept_name == department_name).distinct().all()]
    Dict_doctor_name = {x.doctor_id:x.doctor_name for x in Doctor.query.filter(Doctor.dept_name == department_name).all()}

    Dict_empty_beds = {x:0 for x in List_doctor_id}
    for doctor_id in List_doctor_id:
        empty_beds = Bed.query.filter(Bed.doctor_id == doctor_id, Bed.used_status == 0).count()
        print(f"{doctor_id}的空床数量为{empty_beds}")
        Dict_empty_beds[doctor_id] = empty_beds
    
    
    empty_beds = sorted(Dict_empty_beds.items(),key = lambda x:x[1],reverse=True)

    result = []
    for x in empty_beds:
        result.append({"doctor_id":x[0],"doctor_name":Dict_doctor_name[x[0]],"empty_beds":x[1]})

    return utils.custom_jsonify((result))

@api_bp.route('/predict',methods=['POST'])
def Get_predict_days():
    data = request.get_json()
    description = data.get("description", "")
    gender = data.get("gender", "male")
    age = data.get("age", 30)

    try:
        # 提取特征并预测住院天数
        features = utils.prepare_features(description, age, gender)
        predicted_days = utils.predict_model.predict([features])[0]

        # 确保为 Python 原生 float 类型
        predicted_days = float(predicted_days)

        return utils.custom_jsonify({"predicted_hospital_days": round(predicted_days, 2)})
    except Exception as e:
        return utils.custom_jsonify({"error": str(e)}), 500

@api_bp.route('/test',methods=['GET'])
def test():
    return utils.custom_jsonify({"test":"test"})

    

    

    











